import { setCookie } from '../utils/auth'
import { getuserinfo } from '../api/article'
import { storage, sessionStorage } from '../utils/storage';
/**
 * 封装操作ipc首页下载到本地文件的方法
 */
let id_file:any = []
export const download_file2 = (url: string, article_id: any) => {
    let arr = id_file.filter(item => item === article_id) // 判断是否相同存在满足条件的元素
    console.log(arr,'arrarrarrarrarrarrarr')
    return new Promise((resolve, reject) => {
        if(arr.length == 0) {
            id_file.push(article_id)
            // 下载
            window.electron.ipcRenderer.invoke('download-file-request2', `https://www.huaicaikeyu.cn`+url).then((res) => {
                console.log('download-file',res)
                id_file = id_file.filter((items:any) => items !== article_id);
                resolve(res)
            }).catch((error) => {
                console.log(error); // 输出下载错误信
                reject(JSON.stringify({ success: false, message: `下载文件失败: ${error.message}` }))
            });
        } else {

        }
    })
}
/**
 * 封装操作ipc文章列表下载到本地文件的方法
 */
let id_arr:any = []
export const download_file = (url: string, article_id: any) => {
    let arr = id_arr.filter(item => item === article_id) // 判断是否相同存在满足条件的元素
    console.log(arr,'arrarrarrarrarrarrarr')
    return new Promise((resolve, reject) => {
        if(arr.length == 0) {
            id_arr.push(article_id)
            // 下载
            window.electron.ipcRenderer.invoke('download-file-request', `https://www.huaicaikeyu.cn`+url).then((res) => {
                console.log('download-file',res)
                id_arr = id_arr.filter((items:any) => items !== article_id);
                resolve(res)
            }).catch((error) => {
                console.log(error); // 输出下载错误信
                reject(JSON.stringify({ success: false, message: `下载文件失败: ${error.message}` }))
            });
        } else {

        }
    })
}

// 从返回的header中解析出token
export const GetuserInfo = (cookie,site_id:any) => {
    // const rawString = `PSTM=1742953851; H_PS_PSSID=60277_61027_62347_62373_62426_62474_62484_62515_62456_62454_62452_62451_62611_62327_62636_62675_62676_62686_62702_62619_62719; BAIDUID=31E0E4767567DF3D74C5DCFF126E00EF:FG=1; BIDUPSID=9783AE509A6A036AAC8B53CCEB41763C; theme=bjh; BAIDUID_BFESS=31E0E4767567DF3D74C5DCFF126E00EF:FG=1; ZFY=Be4LHrSnoZzN9wROgosZINfHqypBOTXrxNpi6RxddhM:C; H_WISE_SIDS=60277_61027_62347_62373_62426_62474_62484_62515_62456_62454_62452_62451_62611_62327_62636_62675_62676_62686_62702_62619_62719; PSINO=2; delPer=0; BDORZ=B490B5EBF6F3CD402E515D22BCDA1598; MAWEBCUID=web_xuYrUIGqoDFcDqfLPQAIrATXmZThZIVUICxIYTYVunYwTiruPc; ppfuid=FOCoIC3q5fKa8fgJnwzbE67EJ49BGJeplOzf+4l4EOvDuu2RXBRv6R3A1AZMa49I27C0gDDLrJyxcIIeAeEhD8JYsoLTpBiaCXhLqvzbzmvy3SeAW17tKgNq/Xx+RgOdb8TWCFe62MVrDTY6lMf2GrfqL8c87KLF2qFER3obJGkjS1Q+e/k7Rs6uiFpI37bSGEimjy3MrXEpSuItnI4KD5thIR0P/sZXxwB1HCAWjB1yrkwuZ9ttGifVVdVG8MZawJNJ2LOzm6Zwe09Yr1CX6RJsVwXkGdF24AsEQ3K5XBbh9EHAWDOg2T1ejpq0s2eFy9ar/j566XqWDobGoNNfmfpaEhZpob9le2b5QIEdiQez0E9SVndeXkd9EampG0PcXhLZ126CPFCIEuj/nWa+RPzg/CQV+t396RcQ+QB5B6TasmgOrJ40n63OsKSOpoSLpklEtTKfx5hHc9j4nurRrdQxO5x673r3WZWOB4sULM6VXVSGGnkUB7qA0khSm2nsQwBpdgqbXUb4lU+zNAV2n0AktybhhKxhReRo8jZOXronbjpyaNZANNqEA4g1HmtdHmv/tVUjVExnyBvjSrtrPu8IrnpcuigpPlr6uwWt/lm7TLIKKJqASWGtMQ6010Ekmrx4fAQe4UGeL1qFLCkLuVsqRTBoofr21/QMVXuElE6IsRNIWWghWQd3Lf4jYlSvUuymUDPSEyRa3+0Ti1dVRXtBxMNNlZL/aYKhL8ZXc31rBDqIzqGz8FaOWCcRrX7mFbQV3Cg0pV2IqYt/XyoW9JzPR+cLzrlLnoqS+rLXLnnkUprNdxn+PjQUm/6IsYGfeeSSAeWd7rUjwjsqG1CAideOw1L36a14YJP++P+kS+Sb5mK1x49t/bVAyV1GuW/Di4WdaYtTzhOHb0ypS5VHS/QoLlXJRRrnkhdcvkOKSMqWWQFRlkehXy2fiJffLYWrAf2pIJo//4JrEUhZWbH4V+AFGQM9PC1eNi2DOZbvibR8NTYxlrGkFlkXxi6t+hxhyYN1zEUp6ggVCZWoCgBT7dhxdC3bEpOFlnJXW/ewK+fOJ1Rm0oz1xFFR9FYG1BJvnQA8z6Cz/jTzGDsocIHwA4qlml8ik+FDREmF7DwZHRpOpiwmjUhELAzdRtuu+0nt6o8w3MlwZxJhxBabUW5sicyie973hz6nxWLbBzvYx9F54WJPMynUbqkO3Z7jSA8MZt1Aj6NtrhSNGXID70JtNZcYUpaI4ZXCZpGIlSF+pB7KTLoU96dsmC3+9Ar1MCJM; PHPSESSID=299kb9o6dete9ovglqhnmdovp2; BDUSS=EtMnk0TGlQYjdtfm03U2paaG5xRUtJSS14MjM3YnA5dFRNb05qcGcwMX5vUXhvSUFBQUFBJCQAAAAAAAAAAAEAAAD33pBVTGVlenlvdW5nNjQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAH8U5Wd~FOVnZE; BDUSS_BFESS=EtMnk0TGlQYjdtfm03U2paaG5xRUtJSS14MjM3YnA5dFRNb05qcGcwMX5vUXhvSUFBQUFBJCQAAAAAAAAAAAEAAAD33pBVTGVlenlvdW5nNjQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAH8U5Wd~FOVnZE; RECENT_LOGIN=1; Hm_lvt_f7b8c775c6c8b6a716a75df506fb72df=1742522587,1742811786,1742870916,1743066244; HMACCOUNT=8D1837BF7C33F018; __bid_n=195d6d82709988840286be; Hm_lpvt_f7b8c775c6c8b6a716a75df506fb72df=1743066252; ab_sr=1.0.1_NWY5NTczZjI4MGNkMTdkOGQ3ZTUyNzNkYTU1MzkxZWY3N2YzYzVlMTExZTM5OGE0ZTNlNGY5YThhY2ExZjJkMGM5ZDA2OTBkNDM4ZTI2NTdkYmM5ZTE3OGQwYzk1MDM1NjQzMTgzYjk3ZGEwMzY2ODE1ZDAyODA1MGQwNmEwN2U4Y2E1MjE5YjA0NTg2YjhiOTNkYjk0ZTQ0Yjc2ZTc1ZTIyMjhkZmJkYWI3NTQ1YzkwMDA4MTQzNjVjODFhOGU3ZjhlZTk2M2IyOGQ3MGIyZjhkZmUwZjYxYzEwZDFjZDQzMjIwMTE3MjNhMmQ4NWM4ZDcwYjkzZTMyZjAyMTFlYg==; devStoken=332d2bd8b74d380310893c4eab354dfac38e388a7e470dfc95f550e875f15295; bjhStoken=b6b11ea1937abbec6f3a0774669e625cc38e388a7e470dfc95f550e875f15295; RT="z=1&dm=baidu.com&si=c143b5fc-0fea-4180-aecb-5aadd6a14eeb&ss=m8r4m7sg&sl=3&tt=6gc&bcn=https%3A%2F%2Ffclog.baidu.com%2Flog%2Fweirwood%3Ftype%3Dperf&ld=10ko"`;
    const rawString = cookie
    let arr = {}
    return new Promise((resolve, reject) => {
        rawString.split(';').reduce((acc:any, item:any) => {
            console.log('acc',acc)
            const index = item.indexOf('='); // 找到‘=’的位置
            const [key, value] = [item.substring(0, index),item.substring(index + 1)]; //item.split('=') 先按'='拆分键和值，然后存储到对象中
            arr[key] = encodeURI(value); // 将键值对存储到对象中
        }, {});
          for(let i in arr) {
            setCookie(i.trim(),encodeURI(arr[i]))
            // 设置默认会话的cookies
            const cookie = {
              url: 'https://baijiahao.baidu.com', // 需要设置cookie的URL
              name: i.trim(),
              value: encodeURI(arr[i]),
              path: '/',
              httpOnly: false,
              sameSite: 'no_restriction',
              domain: '.baidu.com' // 注意域名前的点表示这是一个顶级域名
            }
            // electron框架自带的去设置cookie
            window.electron.ipcRenderer.invoke('set-cookie', cookie).then(() => {
              console.log('Cookie 设置成功');
            })
            .catch(error => {
              console.error('设置 Cookie 失败:', error);
            });
          }
          let token:any = sessionStorage.get(`bjhToken_${site_id}`)
          if(token) {
            let K = JSON.parse(token)
            let date = new Date().getTime();
            let OneHour = 1 * 24 * 60 * 60 * 1000
            // 如果大于就是过期了
            if (date - K.startTime > OneHour) {
              sessionStorage.remove(`bjhToken_${site_id}`);
                getuserinfo({cookie: rawString}).then((response:any) => {
                  const result:any = response.data.data
                  console.log('result',result)
                  let Data = Object.assign({ name: 'token', token: response.headers.token }, { startTime: new Date().getTime() });
                  sessionStorage.set(`bjhToken_${site_id}`,JSON.stringify(Data))
                  storage.set(`baijiahao-Token`,response.headers.token)
                  resolve(JSON.stringify({ success: true, message: '设置成功'}))
                }).catch(err => {console.log(err);reject(JSON.stringify({ success: false, message: '请求失败', error: err}))})
            } else {
              storage.set('baijiahao-Token', K.token)
              resolve(JSON.stringify({ success: true, message: '设置成功'}))
            }
          } else {
            getuserinfo({cookie: rawString}).then((response:any) => {
              const result:any = response.data.data
              console.log('result',result)
              let Data = Object.assign({ name: 'token', token: response.headers.token }, { startTime: new Date().getTime() });
              sessionStorage.set(`bjhToken_${site_id}`,JSON.stringify(Data))
              storage.set(`baijiahao-Token`,response.headers.token)
              resolve(JSON.stringify({ success: true, message: '设置成功'}))
            }).catch(err => {console.log(err); reject(JSON.stringify({ success: false, message: '请求失败', error: err}))})
          }
    })
  }